package com.wuzihao.disk.file.service;

import com.obs.services.ObsClient;
import com.obs.services.model.ObjectListing;
import com.obs.services.model.ObsObject;
import com.obs.services.model.TemporarySignatureRequest;
import com.obs.services.model.TemporarySignatureResponse;
import com.wuzihao.disk.mybatis.entity.PtFileEntity;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class FileIoServiceImpl implements FileIoService{

    @Value("${end.point}")
    private String endpoint="";
    @Value("${ak}")
    private String ak="";
    @Value("${sk}")
    private String sk="";
    @Value("${bucket.name}")
    private String bucketName="";

    private ObsClient obsClient = null;

    @Resource
    private FileService fileService;

    private ObsClient getObsClient(){
        if(this.obsClient == null){
            this.obsClient = new ObsClient(ak,sk,endpoint);
        }
        return this.obsClient;
    }

    private Logger logger = LogManager.getLogger(this.getClass());

    @Override
    public void syncFileData() {
        ObjectListing list = getObsClient().listObjects(bucketName);
        List<ObsObject> listObjects = list.getObjects();
        PtFileEntity ptFileEntity = null;
        List<PtFileEntity> ptFileEntityList = new ArrayList<>();

        for (ObsObject obsObject:listObjects){
            ptFileEntity = new PtFileEntity();
            ptFileEntityList.add(ptFileEntity);
            ptFileEntity.setParentUuid("-1");

            logger.info("obsClient obsSize:"  + obsObject.getMetadata().getContentLength());
            ptFileEntity.setFilePath(obsObject.getObjectKey());
            ptFileEntity.setFileUuid(UUID.randomUUID().toString());
            ptFileEntity.setFileCapacity(obsObject.getMetadata().getContentLength());

//            logger.info("obsClient obsKey:" + obsObject.getObjectKey()
//                    + "  obsClient obsSize:"  + obsObject.getMetadata().getContentLength() +
//                    "  obsClient isFolder:" +isFolder(obsObject.getObjectKey()));


            /**
             * 判断是否为文件夹
             */
            if(isFolder(obsObject.getObjectKey())){
                ptFileEntity.setFileType(FILE_TYPE_FOLDER);
            }else{
                ptFileEntity.setFileType(FILE_TYPE_FILE);
            }

            /**
             * 获取文件名称
             */
            ptFileEntity.setFileName(getFileName(obsObject.getObjectKey()));

//            logger.info(ptFileEntity);
        }

        for(PtFileEntity child:ptFileEntityList) {
            for (PtFileEntity parent : ptFileEntityList) {
                //同一文件
                if (child.getFilePath().equals(parent.getFilePath())) {
                    continue;
                }
                //如果父亲是文件跳过
                if (FILE_TYPE_FILE == parent.getFileType()) {
                    continue;
                }

                //文件路径包含父亲节点路径
                if (child.getFilePath().indexOf(parent.getFilePath()) != -1) {
                    child.setParentUuid(parent.getFileUuid());
                }
            }

        }
            logger.info(ptFileEntity);
            fileService.saveFileInfo(ptFileEntityList);
        }


    @Override
    public void mkdirFileInfo(String parentId, String folderName) {
        PtFileEntity entity=fileService.queryFileInfoById(parentId);
        String fileName=folderName;
        if (entity!=null){
            fileName=entity.getFilePath()+FILE_SEPARATOR+folderName;
        }
        fileName=fileName+FILE_SEPARATOR;
        getObsClient().putObject(bucketName,fileName,new ByteArrayInputStream(new byte[0]));
        syncFileData();
    }
    @Override
    public String getShareUrl(String fileUuid) {
        PtFileEntity entity = fileService.queryFileInfoById(fileUuid);
        TemporarySignatureRequest request = new TemporarySignatureRequest();
        request.setBucketName(bucketName);
        request.setObjectKey(entity.getFilePath());
        request.setRequestDate(new Date());
        request.setExpires(60*60);
        TemporarySignatureResponse signature = getObsClient().createTemporarySignature(request);
        String url = signature.getSignedUrl();
        return url;
    }
    @Override
    public String queryShareUrl(String fileUuid, Integer fileValidity) {
        PtFileEntity entity = fileService.queryFileInfoById(fileUuid);
        TemporarySignatureRequest request = new TemporarySignatureRequest();
        request.setBucketName(bucketName);
        request.setObjectKey(entity.getFilePath());
        request.setRequestDate(new Date());
        request.setExpires(60*60*24*fileValidity);
        TemporarySignatureResponse signature = getObsClient().createTemporarySignature(request);
        String url = signature.getSignedUrl();
        return url;
    }


    /**
     * 是否为文件夹
     * @param filePath
     * @return
     */
    private boolean isFolder(String filePath){
        boolean rstB  = false;
        if(filePath.length() > 0){
            String lastStr = filePath.substring(filePath.length() - 1);
            if(FILE_SEPARATOR.equals(lastStr)){
                return true;
            }
        }
        return  rstB;
    }

    /**
     * 获取文件名称
     * @param filePath
     * @return
     */
    private String getFileName(String filePath){
        String fileName = filePath;
        if(filePath.indexOf(FILE_SEPARATOR) != -1){
            String[] fileArray = filePath.split("/");
            if(isFolder(filePath)){
                fileName = fileArray[fileArray.length -1] + FILE_SEPARATOR;
            }else{
                fileName = fileArray[fileArray.length -1];
            }
        }

        return fileName;
    }

}
